package com.giacom.docx4j.test;

import java.io.File;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.datatype.DatatypeFactory;

import org.docx4j.docProps.core.CoreProperties;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.vml.CTShape;
import org.docx4j.vml.CTTextbox;
import org.docx4j.wml.P;
import org.docx4j.wml.Pict;
import org.docx4j.wml.R;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.Tc;
import org.docx4j.wml.Tr;

import com.giacom.document.CtCabecalho;
import com.giacom.document.CtColunaTabela;
import com.giacom.document.CtCorpo;
import com.giacom.document.CtLinhaTabela;
import com.giacom.document.CtParagrafo;
import com.giacom.document.CtPlugin;
import com.giacom.document.CtRegra;
import com.giacom.document.CtSessao;
import com.giacom.document.CtTabela;
import com.giacom.document.Documento;
import com.giacom.document.Documento.Plugins;
import com.giacom.document.Documento.Regras;
import com.giacom.xml.util.JaxbUtil;

/**
 * Gera o documento xml a partir de um docx
 * @author Sandro
 *
 */
public class GeraDocumentoXML {

	public static void main(String[] args) throws Exception {

		String fileName = "resources/teste.docx";
		File sourceFile = new File(fileName);
		
		WordprocessingMLPackage pk = WordprocessingMLPackage.load(new File(fileName));
		MainDocumentPart partDoc = pk.getMainDocumentPart();
		List<Object> content = partDoc.getContent();
		
		CoreProperties cp = pk.getDocPropsCorePart().getJaxbElement();
		System.out.println(cp.getTitle().toString());
		
		/*Documento*/
		Documento doc = new Documento();
		
		//cabecalho
		CtCabecalho c = new CtCabecalho();
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(new Date());
		c.setDataLeitura(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));

		GregorianCalendar cal1 = new GregorianCalendar();
		cal1.setTime(new Date(sourceFile.lastModified()));
		c.setDataDocumento(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal1));
		c.setNomeDocumento(sourceFile.getName());
		doc.setCabecalho(c);
		
		//contador de sessoes
		int s = 0;
		
		CtSessao[] sessaoL = new CtSessao[10];
		
		//Cria uma sessao inicial
		sessaoL[s] = new CtSessao();
		sessaoL[s].setIdSessao(s+1);
		sessaoL[s].setNomeSessao("inicio");
	
		
		int idPar = 0;
		int tableNum = 0; 
		
		for (Object object : content) {
			System.out.println(object);
			
			//cada linha é um objeto P
			if(object instanceof P){
				P p = (P) object;
				if(!String.valueOf(p).isEmpty()){
					CtParagrafo pa = new CtParagrafo();
					pa.setIdParagrafo(++idPar);
					pa.setTextoParagrafo(String.valueOf(p));
					sessaoL[s].getParagrafo().add(pa);
				}
				
				List<Object> cont = p.getContent();
				for (Object object2 : cont) {
					//System.out.println("p content: " + object2);
					if(object2 instanceof R){
						R r = (R) object2;
						List<Object> x1=  r.getContent();
						for (Object object3 : x1) {
							//System.out.println("object3: " + object3);
							JAXBElement<?> e1 = (JAXBElement<?>) object3;
							if(e1.getValue() instanceof Pict){
								Pict pic = (Pict) e1.getValue();
								//System.out.println(pic.getAnyAndAny());
								List<Object> x2 =  pic.getAnyAndAny();
								for (Object object4 : x2) {
									JAXBElement<?> e2 = (JAXBElement<?>) object4;
									if(e2.getValue() instanceof org.docx4j.vml.CTShape){
										org.docx4j.vml.CTShape shape = (CTShape) e2.getValue();
										//System.out.println(shape.getTitle());
										List<JAXBElement<?>> e3 = shape.getPathOrFormulasOrHandles();
										for (JAXBElement<?> jaxbElement : e3) {
											if(jaxbElement.getValue() instanceof org.docx4j.vml.CTTextbox){
												//define a sessao. tudo que vier abaixo deve estar dentro da sessao
												org.docx4j.vml.CTTextbox txt = (CTTextbox) jaxbElement.getValue();
												
												//inicia uma nova sessao
												s = s+1;
												sessaoL[s] = new CtSessao();
												sessaoL[s].setIdSessao(s+1);
												sessaoL[s].setNomeSessao(String.valueOf(txt.getTxbxContent().getEGBlockLevelElts().get(0)));
												System.out.println(txt.getTxbxContent().getEGBlockLevelElts().get(0));
											}
										}
									}
								}
							}
							
						}
						
					}
				}
				
				
				
			}else if(object instanceof JAXBElement){
				JAXBElement<?> element = (JAXBElement<?>) object;
				if(element.getValue() instanceof org.docx4j.wml.Tbl){
					//tabela
					Tbl tbl = (Tbl) element.getValue();
					System.out.println("-------------------------------");
					System.out.println("Tabela " + ++tableNum + ". Linhas = " + tbl.getContent().size());
					System.out.println("-------------------------------");
					int tableLine = 0;
					
					
					CtTabela tab = new CtTabela();
					tab.setDinamica(false);
					tab.setIdTabela(tableNum);
					sessaoL[s].getTabela().add(tab);		
					
					for (Object line : tbl.getContent()) {
						//linha
						//System.out.println(object2);
						
						if(line instanceof org.docx4j.wml.Tr){
							Tr tr = (Tr) line;
							System.out.println("Linha " + ++tableLine + ". Colunas = " + tr.getContent().size());
							
							CtLinhaTabela linha = new CtLinhaTabela();
							linha.setIdLinhaTabela(tableLine);
							
							int tableCol = 0;
							for (Object col : tr.getContent()) {
								//coluna
								//System.out.println(col);	
								JAXBElement colElement = (JAXBElement) col; 
								if(colElement.getValue() instanceof org.docx4j.wml.Tc){
									Tc tc = (Tc) colElement.getValue();
									System.out.print("   Coluna " + ++tableCol + " = ");
									CtColunaTabela coluna = new CtColunaTabela();
									coluna.setIdColunaTabela(tableCol);
									coluna.setTextoColunaTabela(String.valueOf(tc.getContent().get(0)));
									linha.getColunaTabela().add(coluna);
								}else{
									//outro elemento
									System.out.println("**** verificar_y: " + object);
								}
							}
							
							//adiciona uma linha na tabela
							tab.getLinhaTabela().add(linha);
							
						}else{
							//outro elemento
							System.out.println("**** verificar_x: " + object);
						}
					}
				}else{
					//outro elemento
					System.out.println("**** verificar1: " + object);
				}
			}else{
				//outro elemento
				System.out.println("**** verificar2: " + object);
			}
			
		}

		
		// corpo
		CtCorpo corpo = new CtCorpo();
		
		for (int i = 0; i < sessaoL.length; i++) {
			corpo.getSessao().add(sessaoL[i]);	
		}
		
		
		doc.setCorpo(corpo);

		// regras
		Regras regras = new Regras();
		CtRegra regra = new CtRegra();
		regra.setNomeRegra("regra1");
		regra.setTipoRegra("tipo regra");
		regras.getRegra().add(regra);
		doc.setRegras(regras);

		// plugins
		Plugins plugins = new Plugins();
		CtPlugin plugin = new CtPlugin();
		plugin.setNomePlugin("plugin1");
		//plugin.setParametroPlugin("param1");
		plugins.getPlugin().add(plugin);
		doc.setPlugins(plugins);

		fileName = fileName.replaceFirst(".docx", ".xml");
		JaxbUtil.generateXML(fileName, doc);

	}

}
